package top.tagao.kafka.producer.myPartition;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @author Viktor_Liu
 * @Date 2022/8/24 23:21
 */
public class CustomProducerMyPartition {
    public static void main(String[] args) {

        // 1配置信息
        Properties properties = new Properties();
        //服务信息
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"47.106.86.64:9092");
        //配置序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
        //自定义分区规则
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,MyPartitioner.class.getName());


        // 2. 创建 kafka 生产者的配置对象
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String,String>(properties);

        //3. 发送
        for (int i = 0; i < 5; i++) {
            kafkaProducer.send(new ProducerRecord<>("first","vi"+i), new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e == null) System.out.println(recordMetadata.partition());
                }
            });
        }

        kafkaProducer.close();
    }

}
